env.BUILD_USER_NAME = ''
env.BUILD_USER_EMAIL = ''
pipeline {
    agent any
    environment {
        POD_RUN_PORT = 1850
    }
    stages {
        stage('Set Build User') {
            steps {
                script {
                    wrap([$class: 'BuildUser']) {
                        buildDescription "构建人：${BUILD_USER}"
                        script{
                            env.BUILD_USER_NAME="${BUILD_USER}"
                            env.BUILD_USER_EMAIL="${BUILD_USER_EMAIL}"
                            env.PATH=env.NODE_HOME+"/bin:"+env.YARN_HOME+"/bin:"+env.PATH
                        }
                    }
                }
            }
        }
        stage('Clone Source') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/main']], extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'admin_root']], userRemoteConfigs: [[credentialsId: 'ssh', url: 'ssh://git@gitlab.meilinxian.cn:22/mlx/mlx-admin.git']]])
            }
        }
        stage('Merge Project') {
            steps {
                sh '''#!/bin/bash
                    echo "start build ..................."
                    if [ -d webroot/ ];then rm -rf webroot/;fi
                    cp -rf admin_root/. webroot/
                    rm -rf webroot/.git
                    rm -rf admin_root*
                    echo "merge success ................."
                    echo $status
                    echo $version
                    if [ "${status}" = "rollback" ]; then
                        echo "do rollback ................."
                        if [ ! -d "./backup/${version}" ]; then
                            echo "backup version not exists"
                            exit 1
                        fi
                        rm -rf webroot
                        cp -rf "./backup/${version}" ./webroot
                        echo "use backup path:./backup/${version}"
                    fi
                    '''
            }
        }
        stage('Echo Config') {
            steps {
                sh '''#!/bin/bash
                    if [ "${status}" = "rollback" ]; then
                        exit 0
                    fi
                    cd webroot
                    echo "
                    server {
                            server_name _;
                            listen 80 default_server;
                            root /var/www/html/webroot;
                            index index.html;
                            access_log off;
                            include traceid.conf;
                    }
                    " > default
                    echo "
                    #!/bin/bash
                    mkdir -p -m 777 /etc/nginx/env
                    mkdir -p -m 777 /tmp/php_cache
                    if [ -f \\"/var/docker_env.sh\\" ]
                    then
                        /bin/bash /var/docker_env.sh
                    fi
                    nginx -g \\"daemon off;\\"
                    " > run.sh
                    echo "
                    FROM registry.meilinxian.cn:5000/phpbaseimage:latest
                    MAINTAINER mlx_admin
                    ENV POD_NODE_ENV=prod
                    ENV POD_APPNAME=mlx_admin_prod
                    ENV NGINX_PROCESS_NUM=2
                    COPY ./ /var/www/html/webroot
                    COPY ./default /etc/nginx/sites-enabled/
                    ENTRYPOINT [\\"/bin/bash\\",\\"/var/www/html/webroot/run.sh\\"]
                    " > Dockerfile
                    cd ..
                    '''
            }
        }
        stage('Buil Source') {
            steps {
                sh '''#!/bin/bash
                    if [ "${status}" = "rollback" ]; then
                        exit 0
                    fi
                    echo "start build webapp ...................."
                    export PATH=$NODE_HOME/bin:$YARN_HOME/bin:$PATH
                    node --version
                    yarn --version
                    cd webroot
                    yarn config set registry https://mirrors.cloud.tencent.com/npm/
                    yarn && yarn build
                    cd ..
                    echo "build webapp success...................."
                    '''
            }
        }
        stage('Buil Docker') {
            steps {
                sh '''#!/bin/bash
                    echo "get docker version ..............."
                    docker -v
                    echo "start docker build ..............."
                    cd webroot
                    mv Dockerfile ./dist
                    mv default ./dist
                    mv run.sh ./dist
                    cd dist
                    docker build -t mlx/mlx_supply_admin_prod:latest .
                    echo "build success ...................."
                    cd ../../
                    docker rmi registry.meilinxian.cn:5000/mlx/mlx_supply_admin_prod:latest
                    docker image tag mlx/mlx_supply_admin_prod:latest registry.meilinxian.cn:5000/mlx/mlx_supply_admin_prod:latest
                    docker push registry.meilinxian.cn:5000/mlx/mlx_supply_admin_prod:latest
                    docker rmi registry.meilinxian.cn:5000/mlx/mlx_supply_admin_prod:latest
                    echo "clean none image ................."
                    docker rm $(docker ps -a | grep " Exited " | awk -F ' ' '{print $1}')
                    docker rmi $(docker images | grep "<none>" | awk -F ' ' '{print $3}')
                    #echo "docker run ........................"
                    echo "#!/bin/bash
                    docker pull registry.meilinxian.cn:5000/mlx/mlx_supply_admin_prod:latest
                    docker kill mlx_supply_admin_prod
                    docker rm mlx_supply_admin_prod
                    docker run -e POD_NAMESPACE=prod -e POD_NUMBER='01' --name mlx_supply_admin_prod --network mlxnet --ip 192.168.88.151 -m 1024m --cpus=4 --restart=always -d registry.meilinxian.cn:5000/mlx/mlx_supply_admin_prod:latest
                    docker rm \\$(docker ps -a | grep \\" Exited \\" | awk -F ' ' '{print \\$1}')
                    docker rmi \\$(docker images | grep \\"<none>\\" | awk -F ' ' '{print \\$3}')
                    echo \\"run success .....................\\"
                    exit 0
                    " > mlx_admin_prod_run.sh
                    echo "backup build ......................"
                    if [ ! -d backup/ ];then mkdir backup/;fi
                    mkdir -p backup/$BUILD_ID/
                    mv ./webroot/dist/ backup/$BUILD_ID/
                    rm -rf ./webroot
                    cd backup
                    back_file_num=10
                    file_num=$(ls -l | grep ^d | wc -l)
                    echo $file_num
                    echo $back_file_num
                    while (( $file_num > $back_file_num ))
                    do
                        old_file=$(ls -rt | head -1)
                        echo "Delete Back File:"$old_file
                        rm -rf "$old_file"
                        let "file_num--"
                    done
                    echo "list backup path .............."
                    ls -la
                    cd ..
                    echo "list workspace ................"
                    ls -la
                    '''
            }
        }
        stage('Deploy Node') {
            steps {
                sshPublisher(publishers: [sshPublisherDesc(configName: 'Worker_1', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: 'sudo bash /home/ubuntu/mlx_admin_prod_run.sh', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: 'home/ubuntu', remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'mlx_admin_prod_run.sh')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true)])
                sshPublisher(publishers: [sshPublisherDesc(configName: 'Worker_2', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: 'sudo bash /home/ubuntu/mlx_admin_prod_run.sh', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: 'home/ubuntu', remoteDirectorySDF: false, removePrefix: '', sourceFiles: 'mlx_admin_prod_run.sh')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true)])
            }
        }
        stage('Complete') {
            steps {
                qyWechatNotification mentionedId: env.BUILD_USER_EMAIL, mentionedMobile: '', webhookUrl: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b2ed1b53-f35e-4f14-9356-0dd392f7e59f'
            }
        }
    }
}